package org.example.hrpc.rpc.core;

import io.netty.channel.Channel;
import org.example.hrpc.common.exception.RemotingException;
import org.example.hrpc.common.spi.loader.ExtensionLoader;
import org.example.hrpc.rpc.message.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class InvocationRunnable implements Runnable{

    private static final Logger logger = LoggerFactory.getLogger(InvocationRunnable.class);
    private final Channel channel;
    private final Request request;


    public InvocationRunnable(Channel channel, Request request) {
        this.channel = channel;
        this.request = request;
    }

    @Override
    public void run() {
        RpcInvocation invocation = (RpcInvocation) request.getData();
        // 根据参数获取对应的protocol
        Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getExtension(invocation.getProtocol());
        logger.info("RpcInvocation: {}, serviceName:{}", invocation, invocation.getTargetServiceUniqueName());
        // 处理请求
        Invoker<?> invoker = null;
        try {
            invoker = protocol.getInvoker(channel, invocation);
        } catch (RemotingException e) {
            throw new RuntimeException(e);
        }
        Result result = invoker.invoke(invocation);

        // Response
        Response response = new Response();
        response.setRequestId(request.getRequestId());
        response.setServiceStatus(ServiceStatus.SUCCESS);
        response.setMessageType(MessageType.SERVICE_RESPONSE);
        response.setSerializationType(SerializationType.HESSIAN);
        response.setResult(result);
        // 返回响应给客户端
        channel.writeAndFlush(response);
        logger.info("Rpc RequestId: {}, response result: {}", request.getRequestId(), result.getValue());
    }
}
